<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" label-width="120"  ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row>
						<el-col :span="8">
								<el-form-item label="编号" prop="classCode">
									<el-input  v-model="state.pageParam.param.tenantCode" clearable/>
								</el-form-item>
						</el-col>
						<el-col :span="8">
								<el-form-item label="名称" prop="className">
									<el-input  v-model="state.pageParam.param.tenantName" clearable/>
								</el-form-item>
						</el-col>
					</el-row>
			</el-form>
			<div class="btnSearchStyle">
				<el-button type="primary" class="ml7" @click="loadList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</div>
		</el-card>
		<el-card>
			<div class="btnStyle">
				<el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
				<el-button type="primary" icon="ele-Edit" @click="updateHandle" :disabled="state.dataListSelections.length !== 1">修改</el-button>
				<el-button type="primary" icon="ele-Edit" @click="setResEditHandle" :disabled="state.dataListSelections.length !== 1">设置资源范围</el-button>
				<el-button type="primary" icon="ele-Edit" @click="orgManger" :disabled="state.dataListSelections.length !== 1">机构权限管理</el-button>
				<el-button type="danger" icon="ele-Delete" @click="deleteHandle" :disabled="state.dataListSelections.length <= 0">删除</el-button>
			</div>
			<el-table :data="state.dataList" @selection-change="selectionChangeHandle" stripe style="width: 100%">
				<el-table-column prop="id" type="selection" header-align="center" align="center" width="50"/>
				<el-table-column prop="tenantCode" header-align="center" align="center" label="编码"/>
				<el-table-column prop="tenantName" header-align="center" align="center" label="名称"/>
				<el-table-column label="操作" width="350">
					<template #default="scope">
						<el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
						<el-button type="primary" link @click="setResEditHandle(scope.row)">设置资源范围</el-button>
						<el-button type="primary" link @click="orgManger(scope.row)">机构权限管理</el-button>
						<el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.pageParam.page"
				background
				v-model:page-size="state.pageParam.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-card>
		<el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible">
			<el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
				<el-form-item label="编号" prop="classCode">
					<el-input v-model="state.submitForm.tenantCode" placeholder="编号" maxlength="200"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="className">
					<el-input v-model="state.submitForm.tenantName" placeholder="名称" maxlength="200"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置资源权限" ref="tenantMenuSet" v-model="state.tenantMenuSetVisible">
			<el-tree :data="state.treeTenantMenuList" ref="treeTenantMenu" node-key="id" :props="state.defaultProps1"  show-checkbox  :check-strictly="false"  :highlight-current="true">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.tenantMenuSetVisible = false">取消</el-button>
					<el-button type="primary" @click="saveTenantMenuSet">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="tenant">
import { ElLoading, ElMessage, ElMessageBox, ElTree, FormInstance } from 'element-plus';
import { ref, reactive, onMounted, nextTick } from 'vue'
import { systemApi } from '/@/api/sys/system-api'
import { useRouter } from 'vue-router'
const queryFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const treeTenantMenu = ref<InstanceType<typeof ElTree>>()
const router = useRouter()
const state = reactive({
	listLoading: false,
	total: 0,
	dataList: [],
	dataListSelections: [],
	pageParam: {
		page: 1,
		pageSize: 10,
		param: {
			tenantCode: '',
			tenantName: ''
		}
	},
	addOrUpdateVisible: false,
	submitForm: {
		id: '',
		tenantCode: '',
		tenantName: '',
		creater: '',
		createTime: '',
		modUser: '',
		modTime: '',
	},
	submitFormRule: {
		tenantCode: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
		tenantName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
	},
	checkTenantId: '',
	tenantMenuSetVisible: false,
	treeTenantMenuList: [],
	tenantResours: [],
	defaultProps1: {
		children: 'children',
		label: 'name',
	},
})
const loadList = () => {
	state.listLoading = true
	systemApi.queryTenantListByPage(state.pageParam).then(data => {
		if (data && data.code === 0) {
			state.dataList = data.data.records
			state.total = data.data.totalRow
		} else {
			state.dataList = []
			state.total = 0
		}
	}).catch(() => {
	}).finally(() => {
		state.listLoading = false
	})
}
// 页面加载时
onMounted(() => {
	// 列表查询
	loadList()
})

//重置
const reSetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	state.pageParam.page = 1
	loadList()
}
const selectionChangeHandle = (val:any) => {
	state.dataListSelections = val
}
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.pageParam.pageSize = val;
	loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.pageParam.page = val;
	loadList()
}
const addOrUpdateHandle = () => {
	state.submitForm = {
		id: '',
		tenantCode: '',
		tenantName: '',
		creater: '',
		createTime: '',
		modUser: '',
		modTime: '',
	}
	state.addOrUpdateVisible = true
}
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
	state.submitForm = {
		id: '',
		tenantCode: '',
		tenantName: '',
		creater: '',
		createTime: '',
		modUser: '',
		modTime: '',
	}
	if(!row){
		state.submitForm = state.dataListSelections[0]
	} else {
		state.submitForm = row
	}
	state.addOrUpdateVisible = true
}
//打开删除弹窗
const deleteHandle = (id: string | undefined) => {
	var ids = id ? [id] : state.dataListSelections.map(item => {
		return item.id
	})
	if (!ids) {
		ElMessage.error('请选择记录！')
		return
	}
	ElMessageBox.confirm('是否确定删除所选记录', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		systemApi.deleteTenant(ids).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('删除成功')
				loadList();
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error("删除失败")
		})
	})
}
const dataFormSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: boolean) => {
		if (valid) {
			// 提交数据
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			if(!state.submitForm.id) {
				// 新增
				systemApi.addTenant(state.submitForm).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('保存成功')
						// 列表查询
						loadList()
						state.addOrUpdateVisible = false
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('保存失败')
				}).finally(() => {
					loading.close()
				})
			} else{
				systemApi.updateTenant(state.submitForm).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('保存成功')
						// 列表查询
						loadList()
						state.addOrUpdateVisible = false
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('保存失败')
				}).finally(() => {
					loading.close()
				})
			}
		}
	})
}
const setResEditHandle = (row: any | undefined) => {
	if(!row){
		state.checkTenantId = state.dataListSelections[0].id
	} else {
		state.checkTenantId = row.id
	}
	state.tenantMenuSetVisible = true
	const loading = ElLoading.service({
		lock: true,
		text: '处理中',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	systemApi.getSysTenantResTree(state.checkTenantId).then(data => {
		if (data) {
			state.treeTenantMenuList = data.data.tree
			state.tenantResours = data.data.tenantRes
			nextTick(() => {
				checkStation(data.data.tenantRes)
			})
		} else {
			state.treeTenantMenuList = []
		}
		loading.close()
	}).catch(() => {
		loading.close()
	})
}
const checkStation = (asingRes: any) => {
	if (asingRes) {
		var checkArrays = new Array()
		asingRes.forEach((item: any, index: any, arr: any) => {
			if (treeTenantMenu.value!.getNode(item.menuId)) {
				if (treeTenantMenu.value!.getNode(item.menuId).isLeaf) {
					checkArrays.push(item.menuId)
				}
			}
		})
		treeTenantMenu.value!.setCheckedKeys(checkArrays, false)
	} else {
		treeTenantMenu.value!.setCheckedKeys([], false)
	}
}
const saveTenantMenuSet = () => {
	ElMessageBox.confirm('是否确定保存', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		let checkResIds = treeTenantMenu.value!.getCheckedKeys()
		checkResIds = checkResIds.concat(treeTenantMenu.value!.getHalfCheckedKeys())
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		systemApi.setSysTenantMenu(state.checkTenantId, checkResIds).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('设置成功')
				state.tenantMenuSetVisible = false
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error("保存失败")
		}).finally(() => {
			loading.close()
		})
	})
}
const orgManger = (row: any | undefined) => {
	if(!row){
		router.push({path: '/sys/org', query: {tenant: state.dataListSelections[0].id}}) 
	} else {
		router.push({path: '/sys/org', query: {tenant: row.id}})
	}
}
</script>